package com.maimang.platform.controller.common;

import com.maimang.platform.base.Result;
import com.maimang.platform.common.config.Global;
import com.maimang.platform.common.utils.file.FileUploadUtils;
import com.maimang.platform.common.utils.file.FileUtils;
import com.maimang.platform.config.ServerConfig;
import com.maimang.platform.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname CommonController
 * @description <br>通用请求处理</br>
 * @date 2019-08-01 11:07
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/common")
public class CommonController {

	/**
	 * 文件上传路径
	 */
	public static final String UPLOAD_PATH = "/profile/upload/";

	private static final Logger log = LoggerFactory.getLogger(CommonController.class);

	@Autowired
	private ServerConfig serverConfig;

	/**
	 * 文件导出下载
	 *
	 * @param fileName 文件名
	 * @param delete   是否删除源文件
	 * @param response
	 * @param request
	 */
	@GetMapping("/download")
	public void fileDownload(HttpServletResponse response, HttpServletRequest request, String fileName, Boolean delete) {
		try {
			if (!FileUtils.isValidFileName(fileName)) {
				throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
			}
			// String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
			String filePath = Global.getDownloadPath() + fileName;

			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
			FileUtils.writeBytes(filePath, response.getOutputStream());
			if (delete) {
				FileUtils.deleteFile(filePath);
			}
		} catch (Exception e) {
			log.error("下载文件失败", e);
		}
	}

	/**
	 * 多文件上传
	 *
	 * @param file 文件(可以多个)
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/upload")
	@ResponseBody
	public Result uploadFile(MultipartFile file) throws Exception {
		try {
			// 上传文件路径
			String filePath = Global.getUploadPath();
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(filePath, file);
			String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;
			return Result.SUCCESS("200", "上传成功")
					.add("fileName", fileName)
					.add("url", url);
		} catch (Exception e) {
			return Result.FAIL(500, e.getMessage());
		}
	}

}